// TypeScript
// import { v2 as webdav } from 'webdav-server'
// import * as js from '@webdav-server/javascript'
// JavaScript
const webdav = require("webdav-server").v2;
const wsjs = require("@webdav-server/javascript");

const server = new webdav.WebDAVServer({
  // [...]
  autoLoad: {
    // [...]
    serializers: [
      new wsjs.JavascriptSerializer(),
      // [...]
    ],
  },
});

const jsFileSystemEval = new wsjs.JavascriptFileSystem({
  useEval: true,
});
const jsFileSystemExec = new wsjs.JavascriptFileSystem({
  useEval: false,
});

server.setFileSystemSync("/eval", jsFileSystemEval, false);
server.setFileSystemSync("/exec", jsFileSystemExec, false);

jsFileSystemEval.openWriteStream(
  server.createExternalContext(),
  "/file1.txt",
  "mustCreate",
  (e, wStream) => {
    if (e) throw e;
    wStream.end('return "Helloooooooooooooooooooooooooooooooo file 1!";');
  }
);
jsFileSystemEval.openWriteStream(
  server.createExternalContext(),
  "/file2.txt",
  "mustCreate",
  (e, wStream) => {
    if (e) throw e;
    wStream.end(
      'systemCallback("Helloooooooooooooooooooooooooooooooo file 2!");'
    );
  }
);
jsFileSystemEval.openWriteStream(
  server.createExternalContext(),
  "/npm-WebDAV-Server.html",
  "mustCreate",
  (e, wStream) => {
    if (e) throw e;
    wStream.end(
      "const request = require('request'); \
            \
        request({ \
            url: 'https://github.com/OpenMarshal/npm-WebDAV-Server' \
        }, (e, res, body) => { \
            systemCallback(body); \
        })"
    );
  }
);
jsFileSystemExec.openWriteStream(
  server.createExternalContext(),
  "/file.txt",
  "mustCreate",
  (e, wStream) => {
    if (e) throw e;
    wStream.end(
      'console.log("Helloooooooooooooooooooooooooooooooo file exec!");'
    );
  }
);

server.beforeRequest((ctx, next) => {
  console.log(ctx.request.method, ctx.request.url);
  next();
});
server.afterRequest((ctx, next) => {
  console.log(
    ctx.request.method,
    ctx.request.url,
    ctx.response.statusCode,
    ctx.response.statusMessage
  );
  next();
});

server.start((s) => console.log("Ready on port", s.address().port));

// localhost:1900、127.0.0.1:1900
